<template>
  <div class="ai-chat-container">
    <div class="ai-float-button" @click="showChat">
      <img src="@/assets/img/icons/aiIcon.png" alt="AI助手" />
    </div>
    <div
      class="ai-chat-box"
      :class="{ 'ai-chat-box--collapsed': isCollapsed }"
      v-if="isVisible"
    >
      <div class="ai-chat-header">
        <span>AI 探索</span>
        <div class="ai-chat-actions">
          <button @click="toggleCollapse">
            {{ isCollapsed ? "展开" : "收起" }}
          </button>
          <button @click="closeChat">关闭</button>
        </div>
      </div>

      <div class="ai-chat-content" v-show="!isCollapsed" ref="chatContainerBox">
        <!-- 对话内容区域 -->
        <div class="chat-messages" v-if="!showPresetQuestions" ref="chatMsgBox">
          <div class="message user">{{ selectedQuestion }}</div>
          <div class="message ai">
            {{ aiResponse }}
            <div class="message-actions" v-if="isResponseComplete">
              <button class="action-btn" @click="copyResponse">
                <i class="el-icon-document-copy"></i> 复制
              </button>
              <button class="action-btn" @click="regenerateResponse">
                <i class="el-icon-refresh"></i> 重新生成
              </button>
            </div>
          </div>
        </div>
        <!-- 添加预设问题列表 -->
        <div class="preset-questions" v-if="showPresetQuestions">
          <div
            class="question-item"
            v-for="(question, index) in presetQuestions"
            :key="index"
            @click="sendMessage(question)"
            v-html="renderMarkdown(question.question)"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const MarkdownIt = require("markdown-it");
import DOMPurify from "dompurify";
export default {
  name: "AIChatBox",
  props: {
    presetList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      isCollapsed: false,
      inputMessage: "",
      showPresetQuestions: true,
      presetQuestions: [
        {
          question:
            "孙贵生为何选择“七弦辨梦”作为其古琴曲集的名称？<ref>[4]</ref>",
          id: "662e695836424b21d8f9e7dc882877f1",
        },
      ],
      messages: [
        {
          type: "system",
          content: "新人入职的AI助手,可以回答你的问题",
        },
      ],
      selectedQuestion: "",
      aiResponse: "",
      isVisible: false,
      displayedMessage: "",
      isResponseComplete: false,
      currentQuestionId: "",
      chatObserver: null,
    };
  },
  beforeDestroy() {
    if (this.chatObserver) {
      this.chatObserver.disconnect();
    }
  },
  // watch: {
  //   presetList: {
  //     handler(newVal) {
  //       console.log(newVal);
  //       this.presetQuestions = newVal;
  //     },
  //     immediate: true,
  //   },
  // },
  methods: {
    renderMarkdown(content) {
      const md = new MarkdownIt();
      const dirtyHtml = md.render(content);
      return DOMPurify.sanitize(dirtyHtml);
    },
    showChat() {
      this.isVisible = true;
    },
    closeChat() {
      this.isVisible = false;
    },
    copyResponse() {
      navigator.clipboard
        .writeText(this.aiResponse)
        .then(() => {
          this.$message.success("复制成功");
        })
        .catch(() => {
          this.$message.error("复制失败");
        });
    },
    regenerateResponse() {
      this.aiResponse = "";
      this.sendMessage({
        question: this.selectedQuestion,
        id: this.currentQuestionId,
      });
    },
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed;
    },

    sendMessage(question) {
      this.isResponseComplete = false;
      this.showPresetQuestions = false;
      this.selectedQuestion = question.question;
      this.currentQuestionId = question.id;

      this.aiResponse = "";
      this.displayedMessage = "正在获取回答...";
      fetch(`/api/front/deepseek/getAnswer?id=${question.id}`, {
        method: "POST",
        headers: {
          contentType: "application/json;charset=UTF-8",
          databaseCode: "YINWANG",
          token: "",
          installationId: "1234567890",
        },
      })
        .then((response) => response.json())
        .then((res) => {
          if (res.code == 200) {
            this.displayedMessage = "";
            // 逐字显示回答
            this.displayResponse(res.data);
          } else {
            throw new Error(res.message);
          }
          this.displayedMessage = "";
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          this.aiResponse = "获取回答出错，请重试";
        });
    },
    scrollToBottom() {
      const chatMsgBox = this.$refs.chatMsgBox;
      const chatContainerBox = this.$refs.chatContainerBox;
      if (chatMsgBox && chatContainerBox) {
        chatContainerBox.scrollTop = chatContainerBox.scrollHeight;
      }
    },
    displayResponse(response) {
      this.isResponseComplete = false;
      let index = 0;
      const interval = setInterval(() => {
        if (index < response.length) {
          this.aiResponse += response[index];
          index++;
          this.scrollToBottom();
        } else {
          clearInterval(interval);
          this.isResponseComplete = true;
          this.scrollToBottom();
        }
      }, 50);
    },
  },
};
</script>

<style scoped>
.ai-chat-container {
  width: auto;
  height: auto;
  overflow: auto;
}
.ai-float-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 35px;
  height: 35px;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  transition: all 0.3s ease;
}

.button-moved {
  bottom: 440px; /* 对话框高度 + 间距 */
}

.ai-float-button img {
  width: 20px;
  height: 20px;
}
.message-actions {
  position: absolute;
  left: 6px;
  bottom: 8px;
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 4px 8px;
  font-size: 12px;
  background: transparent;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  opacity: 0.8;
}

.action-btn i {
  font-size: 14px;
}
.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
  max-height: 100%;
}

.message {
  margin-bottom: 12px;
  padding: 10px 12px;
  border-radius: 4px;
  max-width: 80%;
  word-break: break-all;
  line-height: 1.5;
  position: relative;
}

.message.user {
  background: #2563eb;
  margin-left: auto;
  border-radius: 8px 0 8px 8px;
  color: #000;
  position: relative; /* 为了绝对定位的参考 */
  margin-bottom: 40px;
}

.message.ai {
  background: #ffffff;
  margin-right: auto;
  border-radius: 0 8px 8px 8px;
  color: #000;
  position: relative;
  padding-bottom: 40px;
}

.message.ai::before {
  content: "";
  position: absolute;
  left: -10px;
  top: 0;
  border: 5px solid transparent;
  border-right-color: #ffffff;
  border-top-color: #ffffff;
}
.preset-questions {
  padding: 10px 16px;
  border-top: 1px solid #eee;
}

.question-item {
  padding: 8px 12px;
  margin: 6px 0;
  background: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.question-item:hover {
  background: #e3f2fd;
}

.ai-chat-box {
  position: fixed;
  right: 20px;
  bottom: 70px;
  width: 320px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.ai-chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f5f5;
  border-radius: 8px 8px 0 0;
}

.ai-chat-content {
  height: 400px;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
  overflow-y: auto;
}

.message {
  margin-bottom: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  max-width: 80%;
}

.message.system {
  background: #f5f5f5;
  margin: 0 auto 12px;
  text-align: center;
}

.message.user {
  background: #2563eb;
  margin-left: auto;
  color: #fff;
}

.message.ai {
  background: #f5f5f5;
  margin-right: auto;
}

.ai-chat-input {
  padding: 12px;
  border-top: 1px solid #eee;
}

.ai-chat-input textarea {
  width: 100%;
  height: 60px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  margin-bottom: 8px;
}

.ai-chat-input button {
  float: right;
  padding: 6px 12px;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.ai-chat-box--collapsed .ai-chat-header {
  border-radius: 8px;
}
</style>
